/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.db.obj.vis.ui.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author yura
 */
public class IOSafeUtils {

    private static final Map<String, byte[]> streamCash =
            new HashMap<String, byte[]>();

    public static String toString(InputStream input) throws IOException {
        String toString = IOUtils.toString(input);
        IOUtils.closeQuietly(input);
        return toString;
    }

    public static InputStream getResourceAsStream(String path)
            throws IOException {
        return getResourceAsStream(IOSafeUtils.class, path);
    }

    public static InputStream getResourceAsStream(Class<?> clazz, String path)
            throws IOException {
        if (streamCash.containsKey(path)){
            return new ByteArrayInputStream(streamCash.get(path));
        }

        InputStream stream = clazz.getResourceAsStream(path);
        byte[] arr = IOUtils.toByteArray(stream);
        stream.close();
        streamCash.put(path, arr);

        return new ByteArrayInputStream(streamCash.get(path));
    }
    
}
